#!/usr/bin/env python
"""
Django Admin配置切换工具

用于在不同的Admin配置模式之间切换：
1. 直接继承AdminSite模式（当前）
2. AdminConfig模式（推荐用于生产环境）

使用方法：
python switch_admin_mode.py [mode]

mode选项：
- multisite: 多站点模式（直接继承AdminSite）
- config: AdminConfig模式
- show: 显示当前模式
"""
import os
import sys
import shutil
from pathlib import Path

# 设置Django环境
BASE_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(BASE_DIR))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'admin_learn_project.settings')

def show_current_mode():
    """显示当前模式"""
    settings_file = BASE_DIR / 'admin_learn_project' / 'settings.py'

    with open(settings_file, 'r', encoding='utf-8') as f:
        content = f.read()

    if 'CustomAdminConfig' in content:
        print("🔧 当前模式: AdminConfig模式")
        print("   - 使用AdminConfig统一管理admin配置")
        print("   - 符合Django最佳实践")
        print("   - 适合企业级应用")
    elif 'django.contrib.admin' in content:
        print("🏗️ 当前模式: 多站点模式")
        print("   - 直接继承AdminSite")
        print("   - 支持多个独立的管理后台")
        print("   - 适合学习和演示")
    else:
        print("❓ 无法识别当前模式")

def switch_to_multisite():
    """切换到多站点模式"""
    print("🔄 切换到多站点模式...")

    settings_file = BASE_DIR / 'admin_learn_project' / 'settings.py'
    backup_file = BASE_DIR / 'settings_backup.py'

    # 备份当前设置
    if settings_file.exists():
        shutil.copy2(settings_file, backup_file)
        print(f"✅ 已备份当前设置到 {backup_file}")

    # 读取原始设置文件内容
    content = '''from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-1af%uvqngu53k6s!5u0w4wh0!6z++d(rev_^%wf=d7y-e^qdk8'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
    'products',
    'orders',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'admin_learn_project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'admin_learn_project.wsgi.application'

# Database
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
STATIC_URL = 'static/'

# Default primary key field type
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# 自定义用户模型
AUTH_USER_MODEL = 'core.CustomUser'

# 媒体文件设置
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
'''

    with open(settings_file, 'w', encoding='utf-8') as f:
        f.write(content)

    print("✅ 已切换到多站点模式")
    print("🌐 可用的管理后台：")
    print("   - /admin/ - 默认管理后台")
    print("   - /super-admin/ - 超级管理员后台")
    print("   - /product-admin/ - 产品管理员后台")
    print("   - /order-admin/ - 订单管理员后台")
    print("   - /user-admin/ - 用户管理员后台")

def switch_to_config():
    """切换到AdminConfig模式"""
    print("🔄 切换到AdminConfig模式...")

    settings_file = BASE_DIR / 'admin_learn_project' / 'settings.py'
    config_file = BASE_DIR / 'settings_with_adminconfig.py'
    backup_file = BASE_DIR / 'settings_backup.py'

    # 备份当前设置
    if settings_file.exists():
        shutil.copy2(settings_file, backup_file)
        print(f"✅ 已备份当前设置到 {backup_file}")

    # 复制AdminConfig设置文件
    if config_file.exists():
        shutil.copy2(config_file, settings_file)
        print("✅ 已切换到AdminConfig模式")
        print("🏢 功能特点：")
        print("   - 使用CustomAdminConfig统一管理")
        print("   - 自动注册模型")
        print("   - 符合Django最佳实践")
        print("   - 支持企业级配置")
        print("🌐 管理后台地址：/admin/")
    else:
        print("❌ 未找到AdminConfig配置文件")

def main():
    if len(sys.argv) < 2:
        print("用法: python switch_admin_mode.py [mode]")
        print("模式选项:")
        print("  multisite - 多站点模式")
        print("  config    - AdminConfig模式")
        print("  show      - 显示当前模式")
        return

    mode = sys.argv[1].lower()

    if mode == 'show':
        show_current_mode()
    elif mode == 'multisite':
        switch_to_multisite()
        print("\n🔄 请重启Django服务器以应用更改")
    elif mode == 'config':
        switch_to_config()
        print("\n🔄 请重启Django服务器以应用更改")
    else:
        print(f"❌ 未知模式: {mode}")
        print("可用模式: multisite, config, show")

if __name__ == '__main__':
    main()
